package team526.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import team526.dao.HistoryDao;
import team526.dao.UserDao;
import team526.entity.User;
import team526.service.UserService;
import team526.util.FileSave;

import java.io.IOException;
import java.util.Date;

/**
 * #Date 2021/9/28 - 10:20
 *
 * @author 王铭 20181620310021
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    HistoryDao historyDao;

    @Autowired
    FileSave fileSave;

    @Override
    public User sign(String email, String info, String username, String password, MultipartFile face_pic) throws IOException {

        if (userDao.createUser(email, info, username, password) > 0) {

            User user = new User();
            user.setPwd(password);
            user.setEmail(email);
            user = userDao.login(user);
            if (face_pic!=null)
                fileSave.saveApi2(user.getUuid() + ".jpg", face_pic.getBytes());
            user.setFace(String.valueOf(user.getUuid()));
            userDao.updateUser(user);
            return user;
        }

        return null;
    }

    @Override
    public Integer saveOrUpdateH(Integer uuid, Integer videoid, Integer watch_to) {
        if (historyDao.selectByPK(uuid, videoid) == null)
            return historyDao.insertOne(uuid, videoid, new Date(), watch_to == null ? 0 : watch_to);
        return historyDao.updateOne(uuid, videoid, new Date(), watch_to == null ? 0 : watch_to);
    }

    @Override
    public User changeInfo(String username, String password, String email, String info, MultipartFile face,User currentUser) throws IOException {
        currentUser.setName(username);
        currentUser.setPwd(password);
        currentUser.setInfo(info);
        if (face!=null&&!face.isEmpty())
            fileSave.saveApi2(currentUser.getFace() + ".jpg", face.getBytes());
        if (userDao.updateUser(currentUser)>0)
            return currentUser;
        return null;
    }
}
